<template>
	<div v-if="dialogData.isShow">
		<el-dialog width="500px" :model-value="true" destroy-on-close :title="dialogData.title" @close="closeDialog">
			<el-form ref="formRef" :rules="rules" :model="form" label-width="90px">
				<el-row>
					<el-col>
						<el-form-item label="资源名称" prop="name">
							<el-input v-model="form.name" placeholder="请输入资源名称" />
						</el-form-item>
					</el-col>
					<el-col>
						<el-form-item label="资源所属" prop="code">
							<el-input v-model="form.code" :disabled="!!dialogData.id" placeholder="请输入学院或年级或班别或创建人或资源所属类别" />
						</el-form-item>
					</el-col>
					<el-col>
						<el-form-item label="专业" prop="major">
							<el-input v-model="form.major" placeholder="请输入专业" />
						</el-form-item>
					</el-col>
					<el-col>
						<el-form-item label="备注">
							<el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<template #footer>
				<div class="dialog-footer">
					<el-button type="primary" @click="submit">确定</el-button>
					<el-button @click="closeDialog">取消</el-button>
				</div>
			</template>
		</el-dialog>
	</div>
</template>

<script setup>
import { getResourceTypeApi, addResourceTypeApi, updateResourceTypeApi } from '@/api/resource';
import { ElMessage } from 'element-plus';
import { reactive, ref } from 'vue';

const formRef = ref();

const emits = defineEmits(['refresh']);

let form = ref({
	name: '',
	code: '',
	major: '', // 专业字段
	remark: '',
});

const rules = {
	name: [{ required: true, message: '请输入类型名称' }],
	code: [{ required: true, message: '请输入类型编码' }],
	major: [{ required: true, message: '请输入专业' }], // 专业字段
};

const getDetails = (id) => {
	getResourceTypeApi(id).then((res) => {
		form.value = Object.assign({}, form.value, res);
	});
};

const dialogData = reactive({
	isShow: false,
	title: '新增',
	id: null,
});

const openDialog = async (row) => {
	dialogData.isShow = true;
	dialogData.title = '新增';
	if (row?.id) {
		dialogData.id = row.id;
		dialogData.title = '编辑';
		getDetails(row.id);
	}
};

const closeDialog = () => {
	dialogData.isShow = false;
	dialogData.id = null;
	form.value = {
		name: '',
		code: '',
		major: '', // 专业字段
		remark: '',
	};
};

const submit = async () => {
	if (!formRef.value) return;
	await formRef.value.validate((valid) => {
		if (valid) {
			if (dialogData.id) {
				updateResourceTypeApi(form.value)
					.then(() => {
						ElMessage.success('操作成功');
						closeDialog();
						emits('refresh');
					})
					.catch((err) => console.error('[ResourceTypeDialog] updateResourceTypeApi 错误：', err));
			} else {
				addResourceTypeApi(form.value)
					.then(() => {
						ElMessage.success('操作成功');
						closeDialog();
						emits('refresh');
					})
					.catch((err) => console.error('[ResourceTypeDialog] addResourceTypeApi 错误：', err));
			}
		} else {
			console.log('[ResourceTypeDialog] 表单校验失败');
		}
	});
};

defineExpose({
	openDialog,
});
</script>

<style scoped></style>
